<template>
    <div class="world-time-converter">
        <div class="tool-header">
            <h1>世界时间转换器</h1>
            <p>在多个城市/时区之间快速换算时间，支持当前时间与自定义时间</p>
        </div>

        <el-row :gutter="20">
            <el-col :span="10">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>基础时间</span>
                            <el-button type="primary" size="small" @click="convertAll">转换</el-button>
                        </div>
                    </template>

                    <el-form label-width="90px" label-position="left">
                        <el-form-item label="参照城市">
                            <el-select v-model="baseTime.zone" placeholder="选择城市">
                                <el-option v-for="zone in timeZones" :key="zone.value"
                                    :label="`${zone.city} (${zone.gmt})`" :value="zone.value" />
                            </el-select>
                            <el-button text size="small" @click="setCurrentTime">当前时间</el-button>
                        </el-form-item>
                        <el-form-item label="日期时间">
                            <el-date-picker v-model="baseTime.datetime" type="datetime" placeholder="选择时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-form>
                </el-card>

                <el-card style="margin-top: 20px;">
                    <template #header>
                        <div class="card-header">
                            <span>自定义时区列表</span>
                            <el-button text size="small" @click="resetList">重置</el-button>
                        </div>
                    </template>

                    <div class="custom-list">
                        <el-select v-model="customZone" placeholder="添加时区" clearable @change="addCustomZone">
                            <el-option v-for="zone in timeZones" :key="zone.value" :label="`${zone.city} (${zone.gmt})`"
                                :value="zone.value" />
                        </el-select>

                        <div class="tags">
                            <el-tag v-for="zone in displayZones" :key="zone.value" closable
                                @close="removeZone(zone.value)">
                                {{ zone.city }}
                            </el-tag>
                        </div>
                    </div>
                </el-card>
            </el-col>

            <el-col :span="14">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>转换结果</span>
                            <el-button text size="small" @click="copyResults">复制结果</el-button>
                        </div>
                    </template>

                    <div v-if="results.length" class="result-list">
                        <el-table :data="results" border stripe>
                            <el-table-column prop="city" label="城市/时区" width="160" />
                            <el-table-column prop="date" label="日期" />
                            <el-table-column prop="time" label="时间" width="140" />
                            <el-table-column prop="gmt" label="GMT" width="120" />
                        </el-table>
                    </div>

                    <el-empty v-else description="选择时间后点击转换即可查看结果" />
                </el-card>
            </el-col>
        </el-row>

        <el-card class="info-card">
            <template #header>
                <div class="card-header">
                    <span>使用说明</span>
                </div>
            </template>
            <ul class="info-list">
                <li>默认展示常用城市，可通过下方选择框添加或移除自定义时区。</li>
                <li>支持手动选择参考时间，也可点击“当前时间”快速填充。</li>
            </ul>
        </el-card>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const timeZones = [
    { city: '北京', value: 'Asia/Shanghai', gmt: 'GMT+08:00' },
    { city: '东京', value: 'Asia/Tokyo', gmt: 'GMT+09:00' },
    { city: '首尔', value: 'Asia/Seoul', gmt: 'GMT+09:00' },
    { city: '悉尼', value: 'Australia/Sydney', gmt: 'GMT+10:00' },
    { city: '新德里', value: 'Asia/Kolkata', gmt: 'GMT+05:30' },
    { city: '莫斯科', value: 'Europe/Moscow', gmt: 'GMT+03:00' },
    { city: '伦敦', value: 'Europe/London', gmt: 'GMT+00:00' },
    { city: '巴黎', value: 'Europe/Paris', gmt: 'GMT+01:00' },
    { city: '纽约', value: 'America/New_York', gmt: 'GMT-05:00' },
    { city: '洛杉矶', value: 'America/Los_Angeles', gmt: 'GMT-08:00' },
    { city: '温哥华', value: 'America/Vancouver', gmt: 'GMT-08:00' },
    { city: '圣保罗', value: 'America/Sao_Paulo', gmt: 'GMT-03:00' },
    { city: '约翰内斯堡', value: 'Africa/Johannesburg', gmt: 'GMT+02:00' },
    { city: '迪拜', value: 'Asia/Dubai', gmt: 'GMT+04:00' }
]

const baseTime = ref({
    zone: 'Asia/Shanghai',
    datetime: dayjs().format('YYYY-MM-DD HH:mm:ss')
})

const defaultZones = ['Asia/Shanghai', 'Europe/London', 'America/New_York', 'Australia/Sydney']
const selectedZones = ref([...defaultZones])
const customZone = ref('')
const results = ref([])

const displayZones = computed(() => {
    return selectedZones.value
        .map(value => timeZones.find(z => z.value === value))
        .filter(Boolean)
})

const setCurrentTime = () => {
    baseTime.value.datetime = dayjs().format('YYYY-MM-DD HH:mm:ss')
}

const resetList = () => {
    selectedZones.value = [...defaultZones]
    results.value = []
}

const addCustomZone = (zone) => {
    if (!zone) return
    if (!selectedZones.value.includes(zone)) {
        selectedZones.value.push(zone)
    }
    customZone.value = ''
}

const removeZone = (zone) => {
    if (selectedZones.value.length <= 1) return
    selectedZones.value = selectedZones.value.filter(item => item !== zone)
}

const convertAll = () => {
    if (!baseTime.value.datetime) {
        ElMessage.warning('请选择基础时间')
        return
    }

    const baseDate = dayjs(baseTime.value.datetime)
    if (!baseDate.isValid()) {
        ElMessage.error('时间格式不正确')
        return
    }

    const baseZone = timeZones.find(z => z.value === baseTime.value.zone)
    if (!baseZone) {
        ElMessage.error('请选择有效的参照城市')
        return
    }

    const baseOffset = getOffsetMinutes(baseZone.gmt)

    results.value = displayZones.value.map(zone => {
        const offset = getOffsetMinutes(zone.gmt)
        const diffMinutes = offset - baseOffset
        const converted = baseDate.add(diffMinutes, 'minute')
        return {
            city: zone.city,
            gmt: zone.gmt,
            date: converted.format('YYYY-MM-DD'),
            time: converted.format('HH:mm:ss')
        }
    })
}

const copyResults = async () => {
    if (!results.value.length) {
        ElMessage.warning('没有可复制的内容')
        return
    }

    const text = results.value
        .map(item => `${item.city} (${item.gmt}) - ${item.date} ${item.time}`)
        .join('\n')

    try {
        await navigator.clipboard.writeText(text)
        ElMessage.success('结果已复制到剪贴板')
    } catch (error) {
        ElMessage.error('复制失败，请手动复制')
    }
}

const getOffsetMinutes = (gmt) => {
    const match = gmt.match(/GMT([+-])(\d{2}):(\d{2})/)
    if (!match) return 0
    const sign = match[1] === '-' ? -1 : 1
    const hours = parseInt(match[2], 10)
    const minutes = parseInt(match[3], 10)
    return sign * (hours * 60 + minutes)
}
</script>

<style scoped>
.world-time-converter {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.tool-header {
    text-align: center;
    margin-bottom: 30px;
}

.tool-header h1 {
    font-size: 2.2rem;
    margin-bottom: 10px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
}

.custom-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.result-list {
    max-height: 420px;
    overflow-y: auto;
}

.info-card {
    margin-top: 30px;
}

.info-list {
    margin: 0;
    padding-left: 20px;
    color: #666;
    line-height: 1.8;
}

@media (max-width: 768px) {
    .card-header {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
    }
}
</style>
